package com.atguigu.springcloud.alibaba.myhandler;

import ch.qos.logback.core.net.SyslogConstants;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.omg.CORBA.SystemException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.util.Date;

@Component
@Primary
public class myHandler1 implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        // Return 429 (Too Many Requests) by default.
        response.setStatus(429);

        StringBuffer url = request.getRequestURL();
        String method = request.getMethod();

        if ("GET".equals(request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
            url.append("?").append(request.getQueryString());
        }

        PrintWriter out = response.getWriter();
        String resource = method.toUpperCase() + ":" + url;

        if (e instanceof FlowException) {
            out.println("resource:  " + resource + "  flowLimit!!!  " + "time:  " + LocalDateTime.now() + "ip:  " + InetAddress.getLocalHost())
            ;

        } else if (e instanceof DegradeException) {
            out.println("resource:  " + resource + "  degradeLimit!!!  " + "time:  " + LocalDateTime.now() + "ip:  " + InetAddress.getLocalHost());

        } else if (e instanceof AuthorityException) {
            out.println("resource:  " + resource + "  authorityLimit!!!  " + "time:  " + LocalDateTime.now() + "ip:  " + InetAddress.getLocalHost());

        } else if (e instanceof SystemBlockException) {
            out.println("resource:  " + resource + "  systemBlockLimit!!!  " + "time:  " + LocalDateTime.now() + "ip:  " + InetAddress.getLocalHost());
        }
        out.flush();
        out.close();
    }

}

